'''
Created on 25/08/2011

@author: Digao
'''
import unittest
import random

class TituloEleitorChecker(object):
    '''
    Classe geradora de numeros de validacao de Titulo de Eleitor
    '''
    multBase = [2,3,4,5,6,7,8,9]
    multUF=[7,8,9]
    
    def checkNumbers(self,number):
        strNumber=('000000000000'+str(number))[-10:]
        sumBase=0
        sumUF=0
        for i in xrange(8):
                sumBase+=int(strNumber[i])*self.multBase[i]
        firstDigit = (sumBase%11)%10
        strNumber+=str(firstDigit)
        for i in xrange(3):
                sumUF+=int(strNumber[i+8])*self.multUF[i]
        secondDigit = (sumUF%11)%10
        digits = str(firstDigit)+str(secondDigit)
        return digits
    def validate(self,number):
        strNumber=('000000000000'+str(number))[-12:]
        digits = self.checkNumbers(strNumber[:-2])
        return digits==strNumber[-2:]
    def fiveDigits(self):
        return ('00000'+str(random.randint(0,99999)))[-5:]
    def generate(self):
        randTitle = self.fiveDigits()+self.fiveDigits()
        checkDigits = self.checkNumbers(randTitle)
        return randTitle+checkDigits
        



class TestGeradorTitulo(unittest.TestCase):
    
    testCases=(('1066444403','02'),
               ('1265934718','72')
               )
    falseCases =(('1066444403','01'),
               ('1265934718','02')
               )
    
    def testManyCases(self):
        obj = TituloEleitorChecker()
        for case in self.testCases:
            self.assertEqual(obj.checkNumbers(case[0]), case[1])
    
    def testManyCases_validate(self):
        obj = TituloEleitorChecker()
        for case in self.testCases:
            self.assertEqual(int(obj.validate(case[0]+str(case[1]))), True)
        for case in self.falseCases:
            self.assertEqual(int(obj.validate(case[0]+str(case[1]))), False)
            
    def testGenerateWithValidate(self):
        obj = TituloEleitorChecker()
        for i in xrange(20):
            self.assertTrue(obj.validate(obj.generate()), "Gerador nao bate com validador")
            
            
    
        
            
        


